package cc.vicp.djx314.starfood.service.order.impls;

import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import cc.vicp.djx314.starfood.service.order.CurrentOrder;

@Component
public class CurrentOrderImpl implements CurrentOrder {
	public static final Logger logger = LoggerFactory.getLogger(CurrentOrderImpl.class);

	private Map<Integer, Date> currentOrders = new Hashtable<Integer, Date>();

	@Override
	public synchronized List<Integer> getCurrentOrder() {
		List<Integer> orderIds = new ArrayList<Integer>();
		Iterator<Integer> idItera = currentOrders.keySet().iterator();
		while (idItera.hasNext()) {
			Integer id = idItera.next();
			orderIds.add(id);
		}
		return orderIds;
	}

	@Override
	public synchronized void addCurrnetOrder(Integer orderId) {
		Date currentTime = new Date();
		currentOrders.put(orderId, currentTime);
	}

	@Override
	public synchronized void removeCurrentOrderByTime(Integer minutes) {
		logger.debug("清除{}分钟前的已选择订单的记录", minutes);
		long time = new Date().getTime() - minutes * 60 * 1000;
		//long time = new Date().getTime();
		Date beforeTime = new Date(time);
		Iterator<Integer> orderIds = currentOrders.keySet().iterator();
		List<Integer> deleteIds = new ArrayList<Integer>();
		while (orderIds.hasNext()) {
			Integer id = orderIds.next();
			Date date = currentOrders.get(id);
			if (date.before(beforeTime)) {
				deleteIds.add(id);
			}
		}
		Iterator<Integer> deleteIdItera = deleteIds.iterator();
		while (deleteIdItera.hasNext()) {
			Integer deleteId = deleteIdItera.next();
			currentOrders.remove(deleteId);
			logger.debug("清除id为{}的订单选择记录使其可以被服务员再次处理", deleteId);
		}
		logger.debug("清理完成");
	}
}